<template>

<div class="portraitUpload-box">
    <el-upload
            ref="upload"
            class="avatar-uploader"
            :limit="1"

            :action="uploadUrl"
            :show-file-list="false"
            :name="uploadFileName"
            :data="{

            }"

            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            @on-change="uploadChange"
    >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="暂无图片">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

</div>

</template>

<script>
    export default {
        name: "PortraitUpload",
        emits:['handleSubmit'],
        props:{
          url:{
              type:String,
              require:true
          }
        },
        data() {
            return {
                uploadFileName:"file",
                uploadUrl:this.$props.url,
                imageUrl:"",
                // imageUrl: 'https://mimiwang.oss-cn-chengdu.aliyuncs.com/image/db13164b-b781-40dc-884d-29b3269824dddog.jpg'

            };
        },
        methods: {

            handleAvatarSuccess(res, file) {
                console.log('uploadok',file)
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            uploadChange(file, fileList){
                console.log(file)
                console.log(fileList)
            }
        },
        watch:{
            url(newV){
                this.uploadUrl=newV
            }
        },
        mounted() {
            // 抛出上传文件权

            this.$emit('handleSubmit',{
                uploadObject:this.$refs.upload,
                submit:this.$refs.upload.submit
            })
        }
    }
</script>

<style scoped >
    .portraitUpload-box{
      background-color: #efefef;
      transition: all 0.3s;

      border: 3px solid #efefef;
    }
    .portraitUpload-box:hover {
      background-color: #ececec;
      border: 3px dotted teal;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>